package com.saiyaemon.blog.controller.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.saiyaemon.blog.pojo.Article;
import com.saiyaemon.blog.pojo.Category;
import com.saiyaemon.blog.service.ArticleService;
import com.saiyaemon.blog.service.ArticleTagService;
import com.saiyaemon.blog.service.CategoryService;
import com.saiyaemon.blog.service.TagService;

/**
 * @author 作者 SaiyaEmon
 * @date 创建时间：2017年12月7日 上午8:24:19
 */
@Controller
public class ManagerCategoryController {
	@Autowired
	ArticleService articleService;

	@Autowired
	CategoryService categoryService;

	@Autowired
	ArticleTagService articleTagService;

	@Autowired
	TagService tagService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "category", method = RequestMethod.GET)
	public ModelAndView showTag(Integer categoryId) {
		ModelAndView modelAndView = new ModelAndView("/manager/category");
		List<Category> allCategories = categoryService.selectAll();
		
		List<Map<String, Object>> categoryArticleInformations = new ArrayList<>();
		

		Category c = new Category();
		if(categoryId!=null)
			c.setId(categoryId);
		List<Category> categories = categoryService.select(c);
		for (Category category : categories) {

			Map<String, Object> categoryArticleInformation = new HashMap<>();

			List<Map<String, Object>> articleInformations = new ArrayList<>();

			Article article = new Article();
			article.setCategoryId(category.getId());

			List<Article> articles = articleService.select(article);
			if(articles!=null&&articles.size()>0)
				categoryArticleInformation.put("category", category);

			for (Article ar : articles) {
				Map<String, Object> selectInformation = articleService.selectInformation(ar);
				articleInformations.add(selectInformation);
			}
			categoryArticleInformation.put("articleInformations", articleInformations);
			categoryArticleInformations.add(categoryArticleInformation);
		}
		System.out.println(categoryArticleInformations);
		modelAndView.addObject("categoryArticleInformations", categoryArticleInformations);
		modelAndView.addObject("allCategories", allCategories);
		for (Map<String, Object> map : categoryArticleInformations) {
			for (String key : map.keySet()) {
				if("articleInformations".equals(key)){
					List<Map<String, Object>> object = (List<Map<String, Object>>)map.get(key);
					if (object.size()!=0) {
						return modelAndView;
					}
				}
			}
		}
		modelAndView.addObject("num", 0);
		return modelAndView;
	}

}
